import javax.swing.event.TableModelListener
import javax.swing.table.*
import javax.swing.*
import net.sshiffon.*
import net.miginfocom.swing.MigLayout
import java.awt.*
import java.awt.event.*
import javax.swing.event.*


actions {
	action(id: "downloadAction",
			name: "Download",
			mnemonic: "D",
			enabled: bind {model.anySelected},
		//	accelerator: shortcut("D"),
			closure: {
				fileList.selectedRows.each({controller.download(it)})
            })
	action(id: "deleteAction",
			name: "Delete",
			//mnemonic: "D",
			enabled: bind {model.anySelected},
			//accelerator: shortcut("D"),
			closure: {
				fileList.selectedRows.each({controller.delete(it)})
            })
    action(id: "mkdirAction",
    		name: "New Dir",
    		closure: {
				   def pane = optionPane(message:'New directory name')
				   def ans = pane.showInputDialog('Make directory','newfolder')
				   controller.mkdir(ans)
				})         
	    action(id: "refreshAction",
	    		name: "Refresh",
	    		closure: {
			controller.refresh()
					})    
	    action(id: "upDirAction",
	    		name: "Up",
	    		closure: controller.upDir
	    		)
	    action(id: "loadFolderAction",
	    		closure: {
					currentFolderName, folderContents ->

	    		    DefaultTableCellRenderer r = new DefaultTableCellRenderer()
	    		    r.setHorizontalAlignment(JLabel.RIGHT)
	    		    r.setFont( java.awt.Font.decode("Monospaced-10") )

	    		    fileList.model = tableModel(list: folderContents) {
	    		            propertyColumn(headerValue:' ',maxWidth: 20, propertyName:'type',
	    		                    cellRenderer: {table,value,selected,hasFocus,row,column ->
	    		                        return label('',icon: imageIcon(value == 'D' ? '/crystal16/folder_yellow.png' : '/crystal16/file_doc.png')) } as TableCellRenderer)
	    		            propertyColumn(headerValue:'Name', propertyName:'name', editable: false)
//	    		                propertyColumn(headerValue:'Details', propertyName:'longname' ,editable: false)
	    		            closureColumn(
	    		              cellRenderer: r,
	    		              header:'Size',
	    		              read: {row -> return row.entry.attrs.dir ? "" : net.sshiffon.FileSizeUtil.format(row.entry.attrs.size, 2) }
	    		              )
	    		            closureColumn(
	    		              header:'Modified',
	    		              read: {row -> return row.entry.attrs.mtimeString }
	    		              )
	    		            closureColumn(
	    		              header:'Permissions',
	    		              read: {row -> return row.entry.attrs.permissionsString }
	    		              )
	    		            closureColumn(
	    		              header:'Owner',
	    		              read: {row ->
	    		                  //logger.debug("!${row.entry.longname}!")
	    		                  if(row.entry.longname.length()>25) {
	    		                    return row.entry.longname.substring(16,25)
	    		                  }
	    		                }
	    		              )
	    		        }
	    		    /*
	    		    def bits= currentFolderName.split('/')
	    		    def subs=[]
	    		    def folderStr=''
	    		    for(Object bit : bits)
	    		    {
	    		        folderStr += bit+'/'
	    		        subs.add(folderStr)
	    		    }
	    		    Collections.reverse(subs)
	    		    //currentFolder.model = new DefaultComboBoxModel(subs.toArray())
	    		    */
	    		})

}

  	panel(id:'mainPanel',layout:new MigLayout("fill"))
    {
        label('Remote Files',font: mainPanel.font.deriveFont(16.0f), constraints: "north")
        separator(orientation: 1)
        toolBar(constraints:'north')
        {
            button(action: upDirAction, icon: imageIcon('/crystal16/folder.png'))
            separator()
            button(action: refreshAction, icon: imageIcon('/crystal16/reload.png'))
            separator()
            button(mkdirAction,icon: imageIcon('/crystal16/folder_new.png'))
        }

        panel(constraints: "north", layout: new MigLayout("fill"))
        {
        	label( text: bind { model.currentFolder } ,id:'currentFolder', constraints:'wrap')
        }
                
                //label(model.currentFolder,id:'currentFolder', constraints:'wrap')
                //comboBox(id:'currentFolder').addActionListener({ evt -> controller.cd(currentFolder.getSelectedItem())} as ActionListener)
                
        
        scrollPane(constraints: "grow") {
          table(id: 'fileList', constraints: 'grow', autoResizeMode: JTable.AUTO_RESIZE_ALL_COLUMNS, autoCreateColumnsFromModel: true) {

        	current.selectionModel.addListSelectionListener({ evt -> 
        	  	model.anySelected = !fileList.selectionModel.selectionEmpty } as ListSelectionListener);
            tableModel(list:model.folderContents)
            {
                //somehow it's necessary for cellRenderer to take hold here ...
               filetypeCol= propertyColumn(headerValue:' ',maxWidth: 20, propertyName:'type',
                        cellRenderer: {table,value,selected,hasFocus,row,column -> label('',icon:imageIcon(value == 'D' ? '/crystal16/folder_yellow.png' : '/crystal16/file_doc.png')) } as TableCellRenderer)
            } 
          }.addMouseListener({ evt -> if(evt.getClickCount() == 2 && !evt.isConsumed() && evt.getID()==java.awt.event.MouseEvent.MOUSE_CLICKED) {
                        evt.consume();
                        logger.debug("double clicked remote file ${fileList.selectedRow} ${model.folderContents.get(fileList.selectedRow).longname}")
                        controller.processEntry(model.folderContents.get(fileList.selectedRow))
                      } } as java.awt.event.MouseListener);
           
        }
        panel(constraints: 'south')
        {
            button(downloadAction,icon: imageIcon('/crystal16/download.png'))
            button(deleteAction,icon: imageIcon('/crystal16/delete.png'))
        }

    }
    mainPanel.add(fileList.getTableHeader(), "north");


    def popupMenu=  popupMenu()
    {
    	menuItem( downloadAction )
    	separator()
    	menuItem( refreshAction )
    	menuItem( mkdirAction )
    	separator()
    	menuItem( deleteAction )
    }
    fileList.addMouseListener({ e -> if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY());} } as java.awt.event.MouseAdapter)
